package com.mqtt;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;



import com.LogWriter;

public class MqttBroker {
	LogWriter logWriter=new LogWriter() {};
	public  void setLogWriter(LogWriter logWriter){
		this.logWriter=logWriter;
	}
	protected void debug(String msg){
		if(logWriter!=null){
			logWriter.writeLog(msg);
		}
	}
	
	MqttConfig mqttConfig=null;
	public MqttBroker(MqttConfig mqttConfig){
		this.mqttConfig=mqttConfig;
	}
	
	private final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	private Connection connection;

	/**
	 * 重新连接服务
	 */
	public void connect() {
		try {
			if(mqttConfig==null){
				debug("error -> no mqtt config");
				return;
			}
			debug("connecting to mqtt...");
			connection=MqttUtil.getConnection(mqttConfig);
			connection.start();
			debug("connect success");
		} catch (Exception e) {
			debug("error -> connect failed and debug is "+e.getMessage());
		}
		
	}
	
	
	public void disconnect(){
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			debug("error -> disconnect failed:"+e.getMessage());
		}
	}

	/**
	 * 发送消息
	 * 
	 * @param topic
	 * @param messageId
	 */
	public boolean sendMessage(String topic, String message) {
		try {
			if (connection == null) {
				//connect();
				return false;
			}
			debug("sending message to " + topic + ", message is " + message);
			MqttUtil.send(connection,topic, message);
			debug("send success");
			return true;
		} catch (Exception e) {
			debug("sned failed -> "+e.getMessage());
		}
		return false;
	}
	
	public void recvMessage(){
		try {
			if (connection == null) {
				connect();
			}
			MqttUtil.recv(connection, mqttConfig.getTopics(), new MessageListener() {
				@Override
				public void onMessage(Message message) {
					try {
						String timeStr=sdf.format(new Date());
						String title=timeStr+" #接收到消息#";
						String content=((TextMessage)message).getText();
						if(!content.trim().startsWith("{")&&!content.trim().startsWith("[")){
							content="\""+content+"\"";
						}
						String data="{\"title\":\""+title+"\",\r\n\"content\":"+content+"}";
						debug(data);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			});
		} catch (Exception e) {
			debug("sned failed -> "+e.getMessage());
		}
	}

	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		disconnect();
	}
}
